//
//  PMDealPaymentViewController.m
//  Manager
//
//  Created by lvzhao on 2020/8/5.
//  Copyright © 2020 吕VV. All rights reserved.
//

#import "PMDealPaymentViewController.h"
#import "PMDealViewModel.h"
#import "PMDealDetailHeadView.h"
#import "LZTableSlideView.h"
#import "LZTableDataModel.h"
#import "LZSortButton.h"
#import "LZMJDIYRefreshHeader.h"
#import "LZMJDIYRefeshFooter.h"
#import "PMScreenDownView.h"
#import "LZOptionModel.h"

@interface PMDealPaymentViewController ()

@property (nonatomic,strong)  PMDealViewModel *viewModel;

@property (nonatomic,strong)  LZTableSlideView *tableView;

@property (nonatomic,strong)  PMDealModel *dealModel;


@end

@implementation PMDealPaymentViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.viewModel.index = 1;
    self.view.backgroundColor = UIColor.whiteColor;

    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self setupUI];

   [self reloadRightItem];
}

//刷新右按钮
- (void)reloadRightItem{
    
    ///!!!:筛选
    self.navigationItem.rightBarButtonItem = nil;
    UIButton *screeningBtn = [UIButton lz_buttonImageName:@"pm_shaixuan" backgroundImageName:@""];
    screeningBtn.frame = CGRectMake(0, 0, 44, 44);
    [LZTool.currentViewController initBarItem:screeningBtn withType:1];
    [screeningBtn addTarget:self action:@selector(screenClick:) forControlEvents:UIControlEventTouchUpInside];
}


///创建UI
- (void)setupUI{
    
        
    PMDealDetailHeadView *headView = [[PMDealDetailHeadView alloc] initViewModel:self.viewModel];
    [self.view addSubview:headView];
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(0);
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(130);
    }];
    

    ///!!!:表格
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(130);
        make.width.mas_equalTo(kScreenWidth);
        make.bottom.mas_equalTo(0);
    }];
    
    ///上拉加载. 下拉刷新
    [self addRefresh];
        
    @weakify(self);
    [self.tableView setCallBlock:^(PMTouchTable touchTable, NSInteger index, LZSortButton *sortBtn) {
         @strongify(self);
        switch (touchTable) {
            case PMTouchTableTop:
            case PMTouchTableTopLeft:
                [self selectTableSortOrder:index sortBtn:sortBtn];
                break;
            case PMTouchTableRight:
                [self selectTableIndex:index];
                break;
            default:
                break;
        }
        
    }];
    
    [self.viewModel.reloadSubject subscribeNext:^(id  _Nullable x) {
        dismiss(nil);
        @strongify(self);
        [self reloadTable:[x intValue]];
    }];
    
    
    
    //获取详情
    showLoadingTitle(@"", nil);
    [self.viewModel getDealDetail:YES];

}

//筛选
- (void)screenClick:(UIButton *)sender{
    
    NSArray *merchantArray = [PMPublicManager sharedInstance].merchantArray;
    NSArray *channelBankArray = [PMPublicManager sharedInstance].channelBankArray;
        
    NSMutableArray *paymentStatus = [LZOptionModel createOptionModel:@[@"处理中",@"付款成功",@"付款失败",@"失败回退中",@"回退完成"] details:@[@"pending",@"paid",@"failed",@"fallback",@"fallback_complete"] key:@"status"];
    
    NSArray *subSelectTitles = @[];
    NSArray *subTitles = @[];
    NSArray *placeholders = @[];

    subSelectTitles = @[merchantArray,channelBankArray,@[],paymentStatus,@[]];
                      subTitles = @[@"商户：",@"付款渠道：",@"订单号：",@"付款状态：",@"时间："];
                      placeholders = @[@"请选择商户",@"付款渠道",@"商户/平台订单号",@"付款状态",@"请选择时间"];
    
    @weakify(self);
    [PMScreenDownView showScreenAlertType:LZAlertTypeTradeScreen cancel:@"重置" sure:@"确定" objectDict:@{@"subTitles":subTitles,@"subSelectTitles":subSelectTitles,@"placeholders":placeholders} cancelBlock:^(id  _Nullable object) {
        @strongify(self);
        [self.viewModel.paramsDictionary removeAllObjects];
    } sureBlock:^(id  _Nullable object) {
        @strongify(self);
        NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] initWithDictionary:object];
        if([dataDictionary[@"endTime"] length] > 0){
            NSString *endTime = [[NSString stringWithFormat:@"%@",dataDictionary[@"endTime"]] componentsSeparatedByString:@" "].firstObject;
            dataDictionary[@"endTime"] = endTime;
        }
        if([dataDictionary[@"startTime"] length] > 0){
            NSString *startTime = [[NSString stringWithFormat:@"%@",dataDictionary[@"startTime"]] componentsSeparatedByString:@" "].firstObject;
            dataDictionary[@"startTime"] = startTime;
        }
        [self.viewModel.paramsDictionary addEntriesFromDictionary:dataDictionary];
        showLoadingTitle(@"", nil);
        [self.viewModel getDealDetail:YES];
        
    }];

}


///刷线表格
- (void)reloadTable:(NSInteger) type{
    
    
    if(type > 3)return;
    
    self.tableView.dataModel = self.viewModel.dataModel;
    [self.tableView.rightTableView.mj_header endRefreshing];
    [self.tableView.rightTableView.mj_footer endRefreshing];
    self.tableView.rightTableView.mj_footer.hidden = NO;
    [self.tableView  dismissEmptyView];
    switch (type) {
        case 0:{
            self.tableView.rightTableView.mj_footer.hidden = YES;
        }
            break;
        default:
            break;
    }
    
    if(self.viewModel.dataModel.dataArray.count == 0){
        self.tableView.rightTableView.mj_footer.hidden = YES;
        [self.tableView tableViewDisplayWithImgName:@"no_data" message:@"暂无数据" contentoffsetY:100 showEmptyView:YES];
    }
}

///添加下拉, 上啦
- (void)addRefresh{
    
    @weakify(self);
    self.tableView.rightTableView.mj_header = [LZMJDIYRefreshHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        @strongify(self);
        [self.viewModel getDealDetail:YES];
 
    }];
    self.tableView.rightTableView.mj_footer = [LZMJDIYRefeshFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        @strongify(self);
        [self.viewModel getDealDetail:NO];
     
    }];
    
    // 不让mj 自适应宽度
    self.tableView.rightTableView.mj_header.autoresizingMask = UIViewAutoresizingNone;
    self.tableView.rightTableView.mj_header.mj_x = -self.viewModel.dataModel.leftWidth;
    // 设置mj宽度
    self.tableView.rightTableView.mj_header.mj_w = K_SCREENWIDTH;
    self.tableView.rightTableView.mj_footer.autoresizingMask = UIViewAutoresizingNone;
    self.tableView.rightTableView.mj_footer.mj_w = K_SCREENWIDTH ;
    self.tableView.rightTableView.mj_footer.mj_x = -self.viewModel.dataModel.leftWidth;
    
}



///选择第几行操作
- (void)selectTableIndex:(NSInteger) index{
    
    PMDealModel *dealModel = self.viewModel.dataArray[index];
    NSMutableArray *subTitles = [[NSMutableArray alloc] init];
    if([dealModel.transfer_status isEqualToString:@"处理中"]){
        [subTitles addObject:@"审核下发"];
    }
    if(!subTitles.count)return;
    @weakify(self);
    [LZToolView showAlertType:LZAlertTypeActionSheet withTitle:@"" message:@"" cancel:@"取消" sure:@"" objectDict:@{@"subTitles":subTitles} cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
        
        switch ([object intValue]) {
            case 0:
            {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    @strongify(self);
                    [self auditIssued:dealModel];
                });
            }
                break;
                
            default:
                break;
        }
        
    }];
}

///审核下发
- (void)auditIssued:(PMDealModel *)dealModel{
    
    //http://www.youquanquan.cn/boot/admin/merchant/auditTransfer
//    order_id: e6685d58-fa9e-419d-a49c-7d8c995a56c2
//    audit_ret: 审核成功123456
//    status: paid
    @weakify(self);
    NSArray *subTitles = [LZOptionModel createOptionModel:@[@"付款成功",@"付款失败"] details:@[@"paid",@"failed"] key:@"status"];
    [LZToolView showAlertType:LZAlertTypeAuditStatus withTitle:@"付款审核" message:@"审核状态" cancel:@"取消" sure:@"确定" objectDict:@{@"subTitles":subTitles,@"placeholder":@"请选择审核状态"} cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
        @strongify(self);
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithDictionary:object];
        dictionary[@"audit_ret"] = dictionary[@"result"]?:@"";
        [dictionary removeObjectForKey:@"result"];
        dictionary[@"order_id"] = dealModel.modelid?:@"";
        [self.viewModel checkAuditTransfer:dictionary];
    }];
}


///选择排序
- (void)selectTableSortOrder:(NSInteger)index sortBtn:(LZSortButton *)sortBtn{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    LZTableRightSubDataModel *subDataModel = nil;
    if(sortBtn.tag == 100){
        subDataModel  = self.viewModel.dataModel.topLeftDataModel;
    } else {
        subDataModel  = self.viewModel.dataModel.topDataModel.itemModelArray[index];
    }
  
    switch (sortBtn.sortStatue) {
        case 1:
            params[@"sortColumn"] = subDataModel.param?:@"";
            params[@"sortOrder"] = @"asc";

            break;
        case 2:
            params[@"sortColumn"] = subDataModel.param?:@"";
            params[@"sortOrder"] = @"desc";
            break;
        default:
            params[@"sortColumn"] = @"";
            params[@"sortOrder"] = @"";
            break;
    }
    
    [self.viewModel.paramsDictionary addEntriesFromDictionary:params];
    showLoadingTitle(@"", nil);
    [self.viewModel getDealDetail:YES];

}

- (PMDealViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[PMDealViewModel alloc] init];
    }
    return _viewModel;;
}

- (LZTableSlideView *)tableView{
    if(!_tableView){
        _tableView = [[LZTableSlideView alloc] initWithFrame:CGRectMake(0, 130, kScreenWidth, 400)];
    }
    return _tableView;
}

@end
